package com.bop.dehong.setting;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.base.dehong.http.RequestCallBack;
import com.base.dehong.util.Base64Coder;
import com.base.dehong.util.LogUtils;
import com.base.dehong.util.PhotoUtil;
import com.base.dehong.util.PreferencesUtils;
import com.base.dehong.util.ToastUtils;
import com.bop.dehong.R;
import com.bop.dehong.base.BaseActivity;
import com.bop.dehong.base.DeHongApp;
import com.bop.dehong.base.TopManager;
import com.bop.dehong.config.Config;
import com.bop.dehong.http.model.GetUserInfoModel;
import com.bop.dehong.http.model.UpDateHeadModel;
import com.bop.dehong.info.EmptyInfo;
import com.bop.dehong.info.UserInfo;
import com.bop.dehong.lock.GesturePwdActivity;
import com.bop.dehong.login.LoginActivity;
import com.bop.dehong.util.ImageLoaderUtils;
import com.bop.dehong.widget.CircleImageView;

/**
 * 个人设置
 * @author TangWenhan/YeFengyun
 *2015-11-19下午5:02:37
 */
public class PersonalSettingActivity extends BaseActivity{

	private static final int PHOTO_REQUEST_TAKEPHOTO = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final int PHOTO_REQUEST_CUT = 3;// 结果
	private static final int PHOTO_REQUEST_SYSTEM = 4;//系统图片返回
	private static final int UPDATE_REQUEST_NICKNAME = 5;//昵称修改
	private static final int UPDATE_REQUEST_NAME = 6;//用户名修改
	private static final int UPDATE_REQUEST_NAMEAUTH = 7;//实名认证修改
	private final int  RESULT_FOR_LOGIN = 101;
	
	private Dialog mChangeAvatarDialog;
	private CircleImageView mAvatarIm;
	private UpDateHeadModel mUpdateHeadModel;
	private TextView mNicknameTv,mNameTv,mBingCardTv;
	private TextView mPhoneTv;
	private GetUserInfoModel mGetInfoModel;
	private String gesturePwd = "";
	private Uri imageUri;//to store the big bitmap
	private Bitmap mOriginal, photo;
	private String uid;

	@Override
	protected void initTop() {
		View mView = getView(R.id.top);
		TopManager manager = new TopManager(mView);
		manager.setTitle(R.string.personal_setting);
		manager.setLeftImageVisibility(View.VISIBLE);
	}

	@Override
	protected void initUI() {
		mAvatarIm = getView(R.id.circleImageView1);
		mNicknameTv  = getView(R.id.nickname);
		mNameTv = getView(R.id.name);
		mBingCardTv = getView(R.id.bingcard);
		mPhoneTv = getView(R.id.phone);
		
		registerOnClickListener(mAvatarIm,
				getView(R.id.set_nickname),
				getView(R.id.set_name_authentication),
				getView(R.id.set_bankcard_info),
				getView(R.id.set_pwd_layout),
				mPhoneTv,
				getView(R.id.gesture_password)
				);
	}
	
	PhotoUtil mPhotoUtil;
	@Override
	protected void initData() {
		Intent intent = getIntent();
		if (intent.hasExtra(Config.UID))
		{
			uid = intent.getStringExtra(Config.UID);
		}else if(DeHongApp.mLoginEntity != null){
			uid = DeHongApp.mLoginEntity.uid;
		}
		mPhotoUtil = new PhotoUtil(this);
		if (DeHongApp.mUserInfo != null) {
			initData(DeHongApp.mUserInfo);
		}else {
			reqInfo();
		}
	}
	
	private void initData(UserInfo info){
		if (info == null) {
			return;
		}
		if (!TextUtils.isEmpty(info.head)) {
			ImageLoaderUtils.getInstance(this).setImageNetResource(mAvatarIm, info.head);
		}
		if (!TextUtils.isEmpty(info.nickname)) {
			mNicknameTv.setText(info.nickname);
		}
		if ("2".equals(info.certification)) {
			mNameTv.setText(info.name);
			getView(R.id.name_arrow).setVisibility(View.GONE);
		}else if ("1".equals(info.certification)) {
			mNameTv.setText("认证中");
			getView(R.id.name_arrow).setVisibility(View.GONE);
		}
		if ("2".equals(info.bank_audit)) {
			mBingCardTv.setText(info.bank_count+"张");
		}else if ("1".equals(info.bank_audit)) {
			mBingCardTv.setText("绑定中");
		}
		if ("2".equals(info.cellphone_audit)) {
			mPhoneTv.setText(info.cellphone);
		}else if ("0".equals(info.cellphone_audit)){
			mPhoneTv.setText("未绑定");
		}else {
			mPhoneTv.setText("绑定中");
		}
		boolean gesture =  PreferencesUtils.getBoolean(
				this, Config.RESET_PSW);
		
		String name = PreferencesUtils.getString(this, Config.USERNAME);
		gesturePwd = PreferencesUtils.getString(this, Config.GESTURE_PWD+name);
		if (!TextUtils.isEmpty(gesturePwd)) {
			((TextView)getView(R.id.gesture_password)).setText("修改");
		}
	}
	
	@Override
	public void onTitleLeftClick(View v) {
		setResult(RESULT_OK);
		super.onTitleLeftClick(v);
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                 && event.getRepeatCount() == 0) {
            setResult(RESULT_OK);
            finishCurrentActivity();
        	return true;
         }
         return super.onKeyDown(keyCode, event);
     }
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode != RESULT_OK) {
			return;
		}
		if (requestCode == PHOTO_REQUEST_TAKEPHOTO) {
			if(imageUri != null){
				mPhotoUtil.startPhotoZoom(imageUri, PHOTO_REQUEST_CUT);
			}
		}else if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data!= null) {
				mPhotoUtil.startPhotoZoom(200, data.getData(), PHOTO_REQUEST_CUT);
			}
		}else if (requestCode == PHOTO_REQUEST_CUT) {
			if(imageUri != null){
				LogUtils.e("picpath", mPhotoUtil.getFile());
				try {
//					UILRequestManager.displayImage("file://" + mPhotoUtil.getFile(), mAvatarIm);
					mOriginal = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
					mAvatarIm.setImageBitmap(mOriginal);
					updateHead(mOriginal);	
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}else{
				Bundle extras = data.getExtras();
				if (extras != null) {
					photo = extras.getParcelable("data");
					ByteArrayOutputStream stream = new ByteArrayOutputStream();
					photo.compress(Bitmap.CompressFormat.JPEG, 100, stream);
					mAvatarIm.setImageBitmap(photo);
					updateHead(photo);
				}
				
			}
		}else if (requestCode == PHOTO_REQUEST_SYSTEM) {
			ToastUtils.show(this, "头像更改成功");
			String headUrl = data.getStringExtra("head");
			ImageLoaderUtils.getInstance(this).setImageNetResource(mAvatarIm, headUrl);
		}else if (requestCode == UPDATE_REQUEST_NICKNAME) {
			String nicknam = data.getStringExtra("nickname");
			DeHongApp.mUserInfo.nickname = nicknam;
			initData(DeHongApp.mUserInfo);
		}else if (requestCode == UPDATE_REQUEST_NAME) {
			reqInfo();
		}else if (requestCode == RESULT_FOR_LOGIN) {
			reqInfo();
		}else if (requestCode == UPDATE_REQUEST_NAMEAUTH) {
			reqInfo();
		}
	}
	private void updateHead(Bitmap bitmap){
		String photoBS64 = Base64Coder.bitmapToBase64(bitmap);
		if (mUpdateHeadModel == null) {
			mUpdateHeadModel = new UpDateHeadModel(this, 0, headCallback);
		}
		showProgressDialog();
		mUpdateHeadModel.doNet(uid, photoBS64);
	}
	RequestCallBack<EmptyInfo> headCallback = new RequestCallBack<EmptyInfo>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}

		@Override
		public void onSuccess(EmptyInfo info) {
			super.onSuccess(info);
			if (!TextUtils.isEmpty(DeHongApp.mUserInfo.head)) {
				ImageLoaderUtils.getInstance(PersonalSettingActivity.this).clearCache();
			}
			ToastUtils.show(PersonalSettingActivity.this, "头像更改成功");
			
		}
		
	};
	
	private void reqInfo(){
		if (!TextUtils.isEmpty(uid)) {
			request();
		}else {
			Intent intent = new Intent(this, LoginActivity.class);
			intent.putExtra(Config.GO_BACK, true);
			startActivityForResult(intent, RESULT_FOR_LOGIN);
		}
		
	}

	private void request() {
		showProgressDialog();
		if (mGetInfoModel == null) {
			mGetInfoModel = new GetUserInfoModel(this, getCallback);
		}
		mGetInfoModel.doNet(DeHongApp.mLoginEntity.uid);
	}
	RequestCallBack<UserInfo> getCallback = new RequestCallBack<UserInfo>() {

		@Override
		public void end() {
			disappearProgressDialog();
		}

		@Override
		public void onSuccess(UserInfo info) {
			super.onSuccess(info);
			DeHongApp.mUserInfo = info;
			initData(DeHongApp.mUserInfo);
		}
		
	};

	private Button mPhotographBt,mAlbumBt,mSystemBt,mCancelBt;
	private void showChangeAvatar(){
		if (mChangeAvatarDialog == null) {
			mChangeAvatarDialog = new Dialog(this, R.style.MyDialogStyle);
			View view = View.inflate(this, R.layout.dialog_change_avatar,null);
			mPhotographBt = getView(view, R.id.dialog_photograph);
			mAlbumBt = getView(view, R.id.dialog_album);
			mSystemBt = getView(view, R.id.dialog_system);
			mCancelBt = getView(view, R.id.dialog_cancel);
			mChangeAvatarDialog.setContentView(view);

			registerOnClickListener(mPhotographBt,mAlbumBt,mSystemBt,mCancelBt);
		}
		mChangeAvatarDialog.show();
	}
	private void dismissChangeAvatar(){
		if (mChangeAvatarDialog != null) {
			mChangeAvatarDialog.dismiss();
		}
	}
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mChangeAvatarDialog != null) {
			mChangeAvatarDialog.dismiss();
			mChangeAvatarDialog = null;
		}
		if (mOriginal != null) {
			mOriginal = null;
		}
		if (photo != null) {
			photo = null;
		}
	}

	@Override
	protected int getContentViewId() {
		TAG = getClass().getName();
		return R.layout.act_personal_setting;
	}

	@Override
	public void onClick(View v)
	{
		switch (v.getId()) {
		case R.id.circleImageView1:
			showChangeAvatar();
			break;
		case R.id.dialog_photograph:
			dismissChangeAvatar();
			String picName = System.currentTimeMillis() + ".jpg";
			mPhotoUtil.setFileName(picName);
			File file = new File(mPhotoUtil.getFile()); 
			imageUri = Uri.fromFile(file);//capture a big bitmap and store it in Uri
			mPhotoUtil.takePhotoByCamera(imageUri, PHOTO_REQUEST_TAKEPHOTO);
			break;
		case R.id.dialog_album:
			dismissChangeAvatar();
			mPhotoUtil.takePhotoByAlbum(PHOTO_REQUEST_GALLERY);
			break;
		case R.id.dialog_system:
			dismissChangeAvatar();
			Intent intent = new Intent(this,SetSystemAvatarActivity.class);
			intent.putExtra(Config.UID, uid);
			startActivityForResult(intent, PHOTO_REQUEST_SYSTEM);
			break;
		case R.id.dialog_cancel:
			dismissChangeAvatar();
			break;
		case R.id.set_nickname:
			Intent intent2 = new Intent(this,SetNicknameActivity.class);
			intent2.putExtra(Config.UID, uid);
			startActivityForResult(intent2, UPDATE_REQUEST_NICKNAME);
			break;
		case R.id.set_name_authentication:
			if (!"2".equals(DeHongApp.mUserInfo.certification)) {
				Intent intent3 = new Intent(this,NameAuthActivity.class);
				intent3.putExtra(Config.UID, uid);
				startActivityForResult(intent3, UPDATE_REQUEST_NAMEAUTH);
			}
			break;
		case R.id.set_bankcard_info:
			Intent intent4 = null;
			if ("2".equals(DeHongApp.mUserInfo.certification)) {
				intent4 = new Intent(this,BankCardActivity.class);
				intent4.putExtra(Config.UID, uid);
				startActivityForResult(intent4, UPDATE_REQUEST_NAME);
			}else {
				ToastUtils.show(this, "您还没有实名认证，请认证后绑卡！");
				intent4 = new Intent(this,NameAuthActivity.class);
				intent4.putExtra(Config.UID, uid);
				startActivityForResult(intent4, UPDATE_REQUEST_NAMEAUTH);
			}
			break;
		case R.id.set_pwd_layout:
			Bundle bundle = new Bundle();
			bundle.putString(Config.UID, uid);
			openActivity(SetPwdActivity.class, bundle);
			break;
		case R.id.gesture_password:
			Intent pwd = new Intent(this,GesturePwdActivity.class);
			int type = 0;
			//如果这个人有账户和密码存在，检查一下是否有手势密码，没有则设置
			if (TextUtils.isEmpty(gesturePwd)) {
				type = 1;
			}else {
				type = 2;
			}
			pwd.putExtra(Config.GO_BACK, true);
			pwd.putExtra(Config.GESTURE_ACTION, type);
			startActivityForResult(pwd, UPDATE_REQUEST_NAME);
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id)
	{
		// TODO Auto-generated method stub
		
	}
}

